import { useState, useEffect } from 'react';
import { Card, Row, Col, Table, DatePicker, Space, Button, Statistic, message, Spin } from 'antd';
import { DollarOutlined, TransactionOutlined, RiseOutlined, FallOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import request from '../utils/request';

const { RangePicker } = DatePicker;

const Stats = () => {
  const [loading, setLoading] = useState(false);
  const [dateRange, setDateRange] = useState([
    dayjs().subtract(7, 'days'),
    dayjs()
  ]);
  const [dailyStats, setDailyStats] = useState([]);
  const [userRanking, setUserRanking] = useState([]);
  const [wineStats, setWineStats] = useState({ byStatus: [], byType: [] });

  useEffect(() => {
    fetchAllStats();
  }, [dateRange]);

  const fetchAllStats = async () => {
    setLoading(true);
    try {
      const [start, end] = dateRange;
      const params = {
        startDate: start.format('YYYY-MM-DD'),
        endDate: end.format('YYYY-MM-DD')
      };

      const [dailyRes, rankingRes, wineRes] = await Promise.all([
        request.get('/stats/daily', { params }),
        request.get('/stats/ranking', { params: { ...params, limit: 10 } }),
        request.get('/stats/wines', { params })
      ]);

      if (dailyRes.success) setDailyStats(dailyRes.data);
      if (rankingRes.success) setUserRanking(rankingRes.data);
      if (wineRes.success) setWineStats(wineRes.data);
    } catch (error) {
      message.error('加载统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 计算汇总数据
  const summary = dailyStats.reduce((acc, item) => ({
    totalRecharge: acc.totalRecharge + item.recharge,
    totalConsume: acc.totalConsume + item.consume,
    totalTransactions: acc.totalTransactions + item.rechargeCount + item.consumeCount
  }), { totalRecharge: 0, totalConsume: 0, totalTransactions: 0 });

  const dailyColumns = [
    { title: '日期', dataIndex: 'date', key: 'date', width: 120 },
    {
      title: '充值金额',
      dataIndex: 'recharge',
      key: 'recharge',
      render: (val) => `¥${val.toFixed(2)}`
    },
    { title: '充值笔数', dataIndex: 'rechargeCount', key: 'rechargeCount' },
    {
      title: '消费金额',
      dataIndex: 'consume',
      key: 'consume',
      render: (val) => `¥${val.toFixed(2)}`
    },
    { title: '消费笔数', dataIndex: 'consumeCount', key: 'consumeCount' }
  ];

  const rankingColumns = [
    { title: '排名', dataIndex: 'rank', key: 'rank', width: 80 },
    { title: '用户名', dataIndex: 'userName', key: 'userName' },
    { title: '手机号', dataIndex: 'phone', key: 'phone' },
    {
      title: '消费总额',
      dataIndex: 'totalConsume',
      key: 'totalConsume',
      render: (val) => `¥${val.toFixed(2)}`,
      sorter: (a, b) => a.totalConsume - b.totalConsume
    },
    { title: '消费次数', dataIndex: 'transactionCount', key: 'transactionCount' }
  ];

  const wineStatusColumns = [
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => status === 'stored' ? '寄存中' : '已取出'
    },
    { title: '记录数', dataIndex: 'count', key: 'count' },
    {
      title: '总数量',
      dataIndex: 'totalQuantity',
      key: 'totalQuantity',
      render: (val) => `${val.toFixed(1)} 瓶`
    }
  ];

  const wineTypeColumns = [
    { title: '酒类型', dataIndex: 'wineType', key: 'wineType' },
    { title: '记录数', dataIndex: 'count', key: 'count' },
    {
      title: '总数量',
      dataIndex: 'totalQuantity',
      key: 'totalQuantity',
      render: (val) => `${val.toFixed(1)} 瓶`
    }
  ];

  return (
    <div>
      <Card
        title="数据统计"
        extra={
          <Space>
            <RangePicker
              value={dateRange}
              onChange={(dates) => dates && setDateRange(dates)}
              format="YYYY-MM-DD"
            />
            <Button type="primary" onClick={fetchAllStats} loading={loading}>
              查询
            </Button>
          </Space>
        }
      >
        {loading ? (
          <div style={{ textAlign: 'center', padding: '50px 0' }}>
            <Spin size="large" />
          </div>
        ) : (
          <>
            <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
              <Col xs={24} sm={8}>
                <Card>
                  <Statistic
                    title="总充值额"
                    value={summary.totalRecharge}
                    precision={2}
                    prefix={<DollarOutlined />}
                    suffix="元"
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={8}>
                <Card>
                  <Statistic
                    title="总消费额"
                    value={summary.totalConsume}
                    precision={2}
                    prefix={<DollarOutlined />}
                    suffix="元"
                    valueStyle={{ color: '#faad14' }}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={8}>
                <Card>
                  <Statistic
                    title="总交易数"
                    value={summary.totalTransactions}
                    prefix={<TransactionOutlined />}
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Card>
              </Col>
            </Row>

            <Card title="每日营业数据" style={{ marginBottom: 16 }}>
              <Table
                columns={dailyColumns}
                dataSource={dailyStats}
                rowKey="date"
                pagination={{ pageSize: 10 }}
                size="small"
              />
            </Card>

            <Row gutter={[16, 16]}>
              <Col xs={24} lg={12}>
                <Card title="用户消费排行" size="small">
                  <Table
                    columns={rankingColumns}
                    dataSource={userRanking}
                    rowKey="userId"
                    pagination={false}
                    size="small"
                  />
                </Card>
              </Col>
              <Col xs={24} lg={12}>
                <Card title="寄存酒统计" size="small">
                  <div style={{ marginBottom: 16 }}>
                    <h4>按状态统计</h4>
                    <Table
                      columns={wineStatusColumns}
                      dataSource={wineStats.byStatus}
                      rowKey="status"
                      pagination={false}
                      size="small"
                    />
                  </div>
                  <div>
                    <h4>按类型统计</h4>
                    <Table
                      columns={wineTypeColumns}
                      dataSource={wineStats.byType}
                      rowKey="wineType"
                      pagination={false}
                      size="small"
                    />
                  </div>
                </Card>
              </Col>
            </Row>
          </>
        )}
      </Card>
    </div>
  );
};

export default Stats;
